﻿using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace server
{
    class SocketServer
    {
        private WebSocketServer server;
        private List<SocketClient> listSocket;
        private Action<IWebSocketConnection> config;

        private string strHost = "0.0.0.0";
        private int intPort = 50000;

        public SocketServer(string strHost = "0.0.0.0", int intPort = 50000)
        {
            this.strHost = strHost;
            this.intPort = intPort;
        }

        public void Init()
        {
            //FleckLog.Level = LogLevel.Debug;
            //this.listSocket = new List<IWebSocketConnection>();
            this.listSocket = new List<SocketClient>();
            this.server = new WebSocketServer("ws://"+ this.strHost +":" + this.intPort); //监听所有的地址的50000端口
            server.RestartAfterListenError = true; // 出错后重启

            this.config = new Action<IWebSocketConnection>(socket => {
                socket.OnOpen = () =>
                {
                    this.OnOpen(socket);
                };
                socket.OnClose = () =>
                {
                    this.OnClose(socket);
                };
                socket.OnMessage = message =>
                {
                    this.OnMessage(socket, message);
                };
                socket.OnError = error =>
                {
                    this.OnError(socket, error);
                };
            });
        }

        public void Start()
        {            
            server.Start(this.config);
        }

        private string GetSocketKey(IWebSocketConnection socket)
        {
            string url = "http://demo.com" + socket.ConnectionInfo.Path; //地址字符串中增加任意域名才能正确解析
            var uri = new Uri(url);
            var collectionQuery = HttpUtility.ParseQueryString(uri.Query);
            return collectionQuery["usercode"];
        }


        private void OnOpen(IWebSocketConnection socket)
        {
            string strKey = this.GetSocketKey(socket);
            Console.WriteLine("Open!");

            this.listSocket.Add(new SocketClient() { 
                key = strKey,
                descriptors = strKey,
                socket = socket
            });
        }

        private void OnClose(IWebSocketConnection socket)
        {
            this.listSocket.RemoveAt(0);
            Console.WriteLine("Close!");
        }

        private void OnMessage(IWebSocketConnection socket, object message)
        {
            SocketClient client = new SocketClient();
            foreach (SocketClient item in this.listSocket)
            {
                if(item.socket == socket)
                {
                    client = item;
                }
            }
            this.SendAll(message.ToString());
            //把消息显示出来
            Console.WriteLine("{0}:{1}", client.key, message);
        }

        private void OnError(IWebSocketConnection socket, object error)
        {
            SocketClient client = new SocketClient();
            foreach (SocketClient item in this.listSocket)
            {
                if (item.socket == socket)
                {
                    client = item;
                }
            }

            listSocket.Remove(client);
            Console.WriteLine(error);
        }

        public void Close()
        {
            Console.WriteLine("close");
        }

        public void SendAll(string message)
        {
            foreach (SocketClient client in this.listSocket)
            {
                client.socket.Send(message);
            }
        }
    }
}
